package com.xiaohe66.web.infrastructure.mybatis.common.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaohe66.web.domain.account.value.AccountId;
import com.xiaohe66.web.domain.common.agg.Tag;
import com.xiaohe66.web.domain.common.value.TagName;
import com.xiaohe66.web.domain.common.repository.TagRepository;
import com.xiaohe66.web.domain.common.value.TagId;
import com.xiaohe66.web.infrastructure.mybatis.common.convert.TagDoConverter;
import com.xiaohe66.web.infrastructure.mybatis.common.mapper.TagMapper;
import com.xiaohe66.web.infrastructure.mybatis.common.model.TagDo;
import com.xiaohe66.web.integration.AbstractMybatisService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author xiaohe
 * @since 2023-01-29 11:53
 */
@Repository
@Slf4j
@RequiredArgsConstructor
public class TagRepositoryImpl
        extends AbstractMybatisService<TagDoConverter, TagMapper, TagDo, Tag, TagId>
        implements TagRepository {

    @Override
    public TagId getOrCreateTagId(AccountId createId, TagName tagName) {

        TagDo query = new TagDo();
        query.setCreateId(createId.getValue());
        query.setName(tagName.getValue());

        TagDo dbTag = getOne(new QueryWrapper<>(query));
        if (dbTag != null) {
            return new TagId(dbTag.getId());

        } else {
            save(query);
            return new TagId(query.getId());
        }
    }

    @Override
    public List<Tag> listByCreateId(AccountId createId) {

        TagDo tagDo = new TagDo();
        tagDo.setCreateId(createId.getValue());

        List<TagDo> list = list(new QueryWrapper<>(tagDo));

        return dataConverter.toAgg(list);
    }
}
